<template>
	<view class="content">
		<!-- <page-head :title="title"></page-head> -->
		<uni-section title="算法介绍" sub-title=" " type="square">
			<uni-card title="TOTP" extra=" " is-full>
				TOTP算法(Time-based One-time Password algorithm)是一种从共享密钥和当前时间计算一次性密码的算法。 它已被采纳为Internet工程任务组标准RFC
				6238，是Initiative for Open Authentication（OATH）的基石，并被用于许多双因素身份验证系统
			</uni-card>
		</uni-section>
		<uni-section title="扫码结果" sub-title=" " >
				<text class="textclass">
					{{result}}
				</text>
			
			<view class="uni-btn-v">
				<button type="primary" @click="scan">扫一扫绑定</button>
			</view>
		</uni-section>
		<uni-section title=" " sub-title=" " type="line">
			<view>绑定码：{{totp}}</view>
		</uni-section>
		<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			:direction="direction" @trigger="trigger" @fabClick="fabClick" />
	</view>
</template>

<script>
	// import Vconsole from 'vconsole'
	import permision from "@/common/permission.js"
	import {
		totpgener,
		genrandom
	} from "@/common/totp.js"
	export default {
		data() {
			return {
				title: '一次性密码生成',
				result: '',
				totp: '',
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#1AAD19',
					buttonColor: '#1AAD19',
					iconColor: '#fff'
				},
				content: [{
						iconPath: '/static/image.png',
						selectedIconPath: '/static/image-active.png',
						text: '亚马逊',
						active: false
					},
					{
						iconPath: '/static/home.png',
						selectedIconPath: '/static/home-active.png',
						text: 'github',
						active: false
					}
				]
			}
		},
		created() {
			// let vConsole = new Vconsole();
		},
		onLoad() {

		},
		methods: {
			trigger(e) {
				console.log(e)
				this.content[e.index].active = !e.item.active
				uni.showModal({
					title: '提示',
					content: `您${this.content[e.index].active ? '选中了' : '取消了'}${e.item.text}`,
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定')
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			},
			fabClick() {
				uni.showToast({
					title: '点击了悬浮按钮',
					icon: 'none'
				})
			},
			testgen() {
				let rand = genrandom();
				this.totp = rand;
			},
			urlparse() {
				// 通过 ? 分割获取后面的参数字符串
				// const url = "otpauth://totp/Amazon:yingge_eu@126.com&secret=ECX3VKG4XX2D5V55";
				let url = decodeURIComponent(this.result);
				const regex = /([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})&secret=(.*)/;
				const match = url.match(regex);
				let obj = {};
				if (match) {
					const email = match[1];
					const domain = match[2];
					const secret = match[3];
					obj.email = email + "@" + domain;
					obj.secret = secret;
				} else {
					return null;
				}
				return obj
			},
			cache(data) {
				//缓存obj
				let userliststr = uni.getStorageSync('userlist');
				let userlist = [];
				console.log(userliststr);
				if (userliststr != "") {
					userlist = JSON.parse(userliststr);
					userlist = userlist.filter(obj => obj.email != data.email);
					userlist.push(data);
				} else {
					userlist.push(data);
				}
				try {
					uni.setStorageSync('userlist', JSON.stringify(userlist));
				} catch (e) {
					// error
				}
			},
			async scan() {
					// #ifdef APP-PLUS
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
					// #endif
					uni.scanCode({
						success: (res) => {
							this.result = res.result
							let obj = this.urlparse()
							if (obj == null) {
								uni.showModal({
									content: '二维码数据异常',
									showCancel: false
								});
								return;
							}
							this.totp = totpgener(obj.secret);
							this.cache(obj);
						},
						fail: (err) => {
							// 需要注意的是小程序扫码不需要申请相机权限

						}
					});
				}
				// #ifdef APP-PLUS
				,
			async checkPermission(code) {
				let status = permision.isIOS ? await permision.requestIOS('camera') :
					await permision.requestAndroid('android.permission.CAMERA');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "需要相机权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
				return status;
			}
			// #endif
		}
	}
</script>

<style>
	.scan-result {
		min-height: 50rpx;
		line-height: 50rpx;
	}

	.content {
		padding: 20rpx;
	}

	.textclass {
		width: 500rpx;
		margin: 5rpx auto;
		padding: 10rpx;
		display: block;
		background-color: #fff;
		text-align: center;
		font-size: 15px;
		color: #353535;
		line-height: 36rpx;
		overflow-wrap: break-word;
	}
</style>